package com.zc.manager;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.zc.getinfo.TelephoneNumInfo;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class TelphoneNumManager {
	private String DB_NAME = "commonnum.db";
	private Context context;

	public TelphoneNumManager(Context context) {
		this.context = context;
	}

	public SQLiteDatabase initDB(String packageName) {
		String dbPath = "/data/data/" + packageName + "/databases/";
		
		File dir = new File(dbPath);
		if (!dir.exists()) {
			dir.mkdir();
		}
		File database = new File(dir, DB_NAME);
		if (database.exists()) {
			database.delete();
		}
		if (!database.exists()) {
			try {
				InputStream in = context.getAssets().open(DB_NAME);
				int size = in.available();
				byte[] buffer = new byte[size];
				in.read(buffer);
				in.close();
				FileOutputStream out = new FileOutputStream(database);
				out.write(buffer);

				out.close();

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();

			}
		}
		return SQLiteDatabase.openOrCreateDatabase(database, null);
	}

	public synchronized List<TelephoneNumInfo> getTelphoneNum(SQLiteDatabase db, String table) {
		List<TelephoneNumInfo> list = new ArrayList<TelephoneNumInfo>();
		String sql = "select * from " + table;
		Cursor cursor = db.rawQuery(sql, null);
		while (cursor.moveToNext()) {
			String name = cursor.getString(cursor.getColumnIndex("name"));
			String number = cursor.getString(cursor.getColumnIndex("number"));
			TelephoneNumInfo info = new TelephoneNumInfo(name, number);
			list.add(info);
		}
		return list;
	}
}
